/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.memberorder.web;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.memberorder.entity.MemberOrder;
import com.jeeplus.modules.memberorder.service.MemberOrderService;

/**
 * 用户订单Controller
 * @author zhych
 * @version 2021-11-16
 */
@RestController
@RequestMapping(value = "/memberorder/memberOrder")
public class MemberOrderController extends BaseController {

	@Autowired
	private MemberOrderService memberOrderService;

	@ModelAttribute
	public MemberOrder get(@RequestParam(required=false) String id) {
		MemberOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = memberOrderService.get(id);
		}
		if (entity == null){
			entity = new MemberOrder();
		}
		return entity;
	}

	/**
	 * 用户订单列表数据
	 */
	@RequiresPermissions("memberorder:memberOrder:list")
	@GetMapping("list")
	public AjaxJson list(MemberOrder memberOrder, HttpServletRequest request, HttpServletResponse response) {
		Page<MemberOrder> page = memberOrderService.findPage(new Page<MemberOrder>(request, response), memberOrder);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取用户订单数据
	 */
	@RequiresPermissions(value={"memberorder:memberOrder:view","memberorder:memberOrder:add","memberorder:memberOrder:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(MemberOrder memberOrder) {
		//  地址解析
		JSONObject jsonObject = JSONObject.parseObject(memberOrder.getAddress());
		String linkman = "";
		String address = "";
		String mobile = "";
		String addressDetail = "";
		if (Objects.nonNull(jsonObject)) {
			linkman = jsonObject.get("linkman").toString();
			address = jsonObject.get("address").toString();
			mobile = jsonObject.get("mobile").toString();
			addressDetail = jsonObject.get("addressDetail").toString();
		}
		return AjaxJson.success().put("memberOrder", memberOrder).put("linkman", linkman).put("address", address).put("addressDetail", addressDetail).put("mobile", mobile);
	}

	/**
	 * 保存用户订单
	 */
	@RequiresPermissions(value={"memberorder:memberOrder:add","memberorder:memberOrder:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(MemberOrder memberOrder, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(memberOrder);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		memberOrderService.save(memberOrder);//保存
		return AjaxJson.success("保存用户订单成功");
	}

	/**
	 * 订单发货
	 */
	@PostMapping("post")
	public AjaxJson post(MemberOrder memberOrder,String mobile, String linkman, String address, String addressDetail, Model model) throws Exception{
		MemberOrder memberOrder1 = memberOrderService.get(memberOrder.getId());
		memberOrder1.setOrderState("3");
		memberOrder1.setDeliveryTime(new Date());
		memberOrder1.setExpNo(memberOrder.getExpNo());
		memberOrder1.setExpress(memberOrder.getExpress());
		JSONObject jsonObject = JSONObject.parseObject(memberOrder1.getAddress());
		jsonObject.put("linkman", linkman);
		jsonObject.put("mobile", mobile);
		jsonObject.put("address", address);
		jsonObject.put("addressDetail", addressDetail);
		memberOrder1.setAddress(jsonObject.toJSONString());
		memberOrderService.save(memberOrder1);
		return AjaxJson.success("发货成功");
	}


	/**
	 * 批量删除用户订单
	 */
	@RequiresPermissions("memberorder:memberOrder:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			memberOrderService.delete(new MemberOrder(id));
		}
		return AjaxJson.success("删除用户订单成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("memberorder:memberOrder:export")
    @GetMapping("export")
    public AjaxJson exportFile(MemberOrder memberOrder, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "用户订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MemberOrder> page = memberOrderService.findPage(new Page<MemberOrder>(request, response, -1), memberOrder);
    		new ExportExcel("用户订单", MemberOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出用户订单记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("memberorder:memberOrder:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<MemberOrder> list = ei.getDataList(MemberOrder.class);
			for (MemberOrder memberOrder : list){
				try{
					memberOrderService.save(memberOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户订单记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条用户订单记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入用户订单失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入用户订单数据模板
	 */
	@RequiresPermissions("memberorder:memberOrder:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "用户订单数据导入模板.xlsx";
    		List<MemberOrder> list = Lists.newArrayList();
    		new ExportExcel("用户订单数据", MemberOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}